package com.yangtzeu.jwc.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yangtzeu.jwc.activity.NewsActivity;
import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.business.BaseParser.ParserListener;
import com.yangtzeu.jwc.business.NewsListParser;
import com.yangtzeu.jwc.business.NewsParser;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.T;

public class IndexFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout mSwipeLayout;
    private Handler myHandler = new MyHandler();
    private List<NewsParser> news = new ArrayList<NewsParser>();
    private ProgressDialog dialog;
    private ProgressBar progressBar;
    private ListView news_list;
    private PopupWindow mPopupWindow;
    private NewsAdapter adapter;
    NewsListParser jwtzParser = new NewsListParser(G.JWTZ, "教务通知");
    NewsListParser jxdtParser = new NewsListParser(G.JXDT2, "教学动态");
    NewsListParser jxjbParser = new NewsListParser(G.JXJB, "教学简报");
    NewsListParser gjxxParser = new NewsListParser(G.GJXX, "高教信息");
    NewsListParser sjjxParser = new NewsListParser(G.SJJX, "实践教学");
    NewsListParser xzzxParser = new NewsListParser(G.XZZX, "下载中心");
    public NewsParser currentPaser;

    public class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String failureMsg;
            switch (msg.what) {
                case G.SHOWPROGRESSBAR:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case G.SHOWPROGRESSDIALOG:
                    dialog = CustomeProgressDialog.show(getActivity(), "正在加载..");
                    break;
                case G.DISMISSPROGRESSBAR:
                    progressBar.setVisibility(View.GONE);
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    adapter.notifyDataSetChanged();
                    break;
                case G.REFRESHFINISH:
                    // MyApplication.getInstance().showShortToast("刷新完成");
                    // news_list.stopRefresh(true);
                    break;
                case G.REFRESHFAILED:
                    failureMsg = msg.getData().getString("msg");
                    MyApplication.getInstance().showShortToast(failureMsg);
                    // news_list.stopRefresh(false);
                case G.LOADFAILED:
                    T.showLong(getActivity(), "数据加载失败，请检查网络或确保教务处可以访问");
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    if (mSwipeLayout != null) {
                        mSwipeLayout.setRefreshing(false);
                    }
                    break;
                case G.LOADFINISH:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    Intent intent = new Intent();
                    intent.putExtra("title", currentPaser.title);
                    intent.putExtra("content", currentPaser.toWap());
                    intent.putExtra("url", currentPaser.path);
                    intent.setClass(getActivity(), NewsActivity.class);
                    startActivity(intent);
                    break;
                case 100:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.clear();
                    news.addAll(jwtzParser.newses);
                    adapter.notifyDataSetChanged();
                    getJxdt(msg.getData().getBoolean("fromCache"));
                    if (mSwipeLayout != null) {
                        mSwipeLayout.setRefreshing(false);
                    }
                    break;
                case 101:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.addAll(jxdtParser.newses);
                    adapter.notifyDataSetChanged();
                    getJxjb(msg.getData().getBoolean("fromCache"));
                    break;
                case 102:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.addAll(jxjbParser.newses);
                    adapter.notifyDataSetChanged();
                    getGjxx(msg.getData().getBoolean("fromCache"));
                    break;
                case 103:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.addAll(gjxxParser.newses);
                    adapter.notifyDataSetChanged();
                    getSjjx(msg.getData().getBoolean("fromCache"));
                    break;
                case 104:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.addAll(sjjxParser.newses);
                    adapter.notifyDataSetChanged();
                    getXzzx(msg.getData().getBoolean("fromCache"));
                    break;
                case 105:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    news.addAll(xzzxParser.newses);
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.index_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSwipeLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.swipe_container);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.main_blue_color,
                R.color.red, R.color.yellow,
                R.color.teal);
        news_list = (ListView) getActivity().findViewById(R.id.news_list);
        // news_list.setXListViewListener(this);
        // news_list.setPullLoadEnable(false, null, null);
        progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_refresh);
        adapter = new NewsAdapter(getActivity(), news, R.layout.news_item);
        news_list.setAdapter(adapter);
        news_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsParser parser = (NewsParser) parent.getItemAtPosition(position);
                if (parser != null) {
                    getNews(parser);
                }
            }
        });
        getJwtz(true);
    }

    private void getJwtz(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                jwtzParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(100);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getJxdt(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                jxdtParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(101);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getJxjb(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                jxjbParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(102);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getGjxx(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                gjxxParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(103);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getSjjx(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                sjjxParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(104);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getXzzx(final boolean fromCache) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                xzzxParser.startParse(new ParserListener() {
                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage(105);
                        Bundle b = new Bundle();
                        b.putBoolean("fromCache", fromCache);
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub
                        myHandler.sendEmptyMessage(G.LOADFAILED);
                    }
                }, fromCache);
            }
        }).start();
    }

    private void getNews(final NewsParser parser) {
        parser.path = parser.path.replaceFirst(G.YANGTZEU_INNER_PATH_PATTERN, G.NEW_JWC);
        if (true||!parser.path.startsWith("http://jwc") && !parser.path.startsWith("jwc")) {
            Intent intent = new Intent();
            intent.putExtra("title", parser.title);
            intent.putExtra("url", parser.path);
            intent.setClass(getActivity(), NewsActivity.class);
            startActivity(intent);
            return;
        }
        myHandler.sendEmptyMessage(G.SHOWPROGRESSDIALOG);
        new Thread(new Runnable() {

            @Override
            public void run() {
                parser.startParse(new ParserListener() {

                    @Override
                    public void finish() {
                        // TODO Auto-generated method stub
                        Message msg = myHandler.obtainMessage();
                        msg.what = G.LOADFINISH;
                        currentPaser = parser;
                        myHandler.sendMessage(msg);
                    }

                    @Override
                    public void failed() {
                        // TODO Auto-generated method stub

                    }
                }, true);
            }
        }).start();
    }

    // 自定义ListView条目绑定适配器
    private final class NewsAdapter extends BaseAdapter {
        private List<NewsParser> data;
        private int resource;
        private LayoutInflater inflater;

        public NewsAdapter(Context context, List<NewsParser> data, int resource) {
            super();
            this.data = data;
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public NewsParser getItem(int position) {
            return this.data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(resource, null);
            }
            // 得到相应条目的控件
            TextView item_title = (TextView) convertView.findViewById(R.id.item_title);
            TextView item_type = (TextView) convertView.findViewById(R.id.item_type);
            TextView item_time = (TextView) convertView.findViewById(R.id.item_time);
            NewsParser parser = getItem(position);
            item_title.setText(parser.title);
            item_type.setText(parser.catalog);
            item_time.setText(parser.time);
            return convertView;
        }
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        getJwtz(false);
    }
}
